//
//  TTDetailShareViewController.m
//  TaoTuo
//
//  Created by admin on 2019/12/10.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDetailShareViewController.h"
#import "TTImageChooseView.h"
#import "TTDetailModel.h"
#import "TTShopCartView.h"
#import <WXApi.h>
#import <Photos/Photos.h>
#import "TTDetailSharePopView.h"
#import <UIView+TYAlertView.h>
#import "YBImageBrowser.h"

@interface TTDetailShareViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UISwitch *waterSwitch;
@property (nonatomic, strong) UISwitch *qrCodeSwitch;

@property (nonatomic, strong) NSMutableArray<UIImage *> *chooseImageArray;
@property (nonatomic, strong) NSMutableArray<TTImageChooseView *> *chooseViewArray;

@property (nonatomic, strong) TTDetailModel *model;
@property (nonatomic, assign) NSInteger saveImagesCount;
@property (nonatomic, strong) TTDetailSharePopView *sharePopView;
///图片加载完成的数量
@property (nonatomic, assign) int imageLoadFinishCount;

@property (nonatomic, strong) NSMutableArray *imgs;

@end

@implementation TTDetailShareViewController

- (instancetype)initWithDetailModel:(TTDetailModel *)model
{
    self = [super init];
    if (self) {
        self.model = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"分享转发";
    
    [self setupSubviews];
    
}

///水印开关
- (void)waterSwitchClick:(UISwitch *)sender
{
    [self.imgs removeAllObjects];
    self.imageLoadFinishCount = 0;
    [self.chooseImageArray removeAllObjects];
    
    BOOL allOn = sender.on && self.qrCodeSwitch.on;
    NSArray *array = allOn ? self.model.Share.ShareWatermarkQrCodeTextImg : (sender.on ? self.model.Share.ShareWatermarkImg : (self.qrCodeSwitch.on ? self.model.Share.ShareWatermarkQrCodeImg : self.model.Share.ShareOriginalImg));
    for (int i = 0; i < self.chooseViewArray.count; i++) {
        NSString *urlStr = array[i];
        TTImageChooseView *view = self.chooseViewArray[i];
        view.imageUrlString = urlStr;
        
        YBIBImageData *imageData = [YBIBImageData new];
        imageData.imageURL = [NSURL URLWithString:urlStr];
        [self.imgs addObject:imageData];
        
    }
}


///二维码开关
- (void)qrCodeSwitchClick:(UISwitch *)sender
{
    [self.imgs removeAllObjects];
    
    self.imageLoadFinishCount = 0;
    [self.chooseImageArray removeAllObjects];
    
    BOOL allOn = sender.on && self.qrCodeSwitch.on;
    NSArray *array = allOn ? self.model.Share.ShareWatermarkQrCodeTextImg : (sender.on ? self.model.Share.ShareWatermarkQrCodeImg : (self.waterSwitch.on ? self.model.Share.ShareWatermarkImg : self.model.Share.ShareOriginalImg));
    for (int i = 0; i < self.chooseViewArray.count; i++) {
        NSString *urlStr = array[i];
        TTImageChooseView *view = self.chooseViewArray[i];
        view.imageUrlString = urlStr;
        
        YBIBImageData *imageData = [YBIBImageData new];
        imageData.imageURL = [NSURL URLWithString:urlStr];
        [self.imgs addObject:imageData];
        
    }
}



- (void)setupSubviews
{
    [self.imgs removeAllObjects];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 85 - StatusBarAndNavBar_Height)];
    [self.view addSubview:_scrollView];
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, self.view.width - 20, 90)];
    _textView.backgroundColor = kSeparatorColor;
    _textView.layer.cornerRadius = 5;
    _textView.text = [NSString stringWithFormat:@"%@（款号：%@）", self.model.Share.ShareTitle, self.model.StandardNumber];
    [self.scrollView addSubview:_textView];
    
    CGFloat chooseViewWH = self.view.width / 3.0;
    for (int i = 0; i < self.model.Share.ShareWatermarkQrCodeImg.count; i++) {
        NSString *imageUrlString = self.model.Share.ShareWatermarkQrCodeImg[i];
        CGFloat x = chooseViewWH * (i % 3);
        CGFloat y = _textView.bottom + 10 + i / 3 * chooseViewWH;
        @weakify(self)
        TTImageChooseView *chooseView = [[TTImageChooseView alloc] initWithFrame:CGRectMake(x, y, chooseViewWH, chooseViewWH) chooseBlock:^(UIImage * _Nullable image, BOOL selected) {
            @strongify(self)
            if (selected) {
                if (![self.chooseImageArray containsObject:image]) {
                    [self.chooseImageArray addObject:image];
                }
            } else {
                [self.chooseImageArray removeObject:image];
            }
            
        } flags:i];
        chooseView.imageUrlString = imageUrlString;
        [self.scrollView addSubview:chooseView];
        [self.chooseViewArray addObject:chooseView];
        
        YBIBImageData *imageData = [YBIBImageData new];
        imageData.imageURL = [NSURL URLWithString:imageUrlString];
        [self.imgs addObject:imageData];
        
        [chooseView.subject subscribeNext:^(NSNumber *  _Nullable x) {
            @autoreleasepool {
                NSInteger i = x.integerValue;
                YBImageBrowser *browser = [YBImageBrowser new];
                browser.dataSourceArray = self.imgs;
                browser.currentPage = i;
                [browser show];
            }
        }];
        
    }
    
    NSInteger t = ceil(self.model.Share.ShareOriginalImg.count / 3.0);
    UIView *waterView = [[UIView alloc] initWithFrame:CGRectMake(0, self.textView.bottom + 20 + t * chooseViewWH, self.view.width, 40)];
    waterView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:waterView];
    
    UILabel *waterLaebl = [UILabel labelWithTitle:@"开启水印" color:UIColorHex(333333) fontSize:15];
    [waterView addSubview:waterLaebl];
    [waterLaebl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(waterView);
    }];
    
    _waterSwitch = [[UISwitch alloc] init];
    _waterSwitch.transform = CGAffineTransformMakeScale(0.8, 0.8);
    _waterSwitch.onTintColor = kMainColor;
    [_waterSwitch addTarget:self action:@selector(waterSwitchClick:) forControlEvents:UIControlEventValueChanged];
    [waterView addSubview:_waterSwitch];
    [_waterSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(waterView).mas_offset(-10);
        make.centerY.equalTo(waterView);
    }];
    
    
    UIView *qrCoderView = [[UIView alloc] initWithFrame:CGRectMake(0, waterView.bottom + 10, self.view.width, 40)];
    qrCoderView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:qrCoderView];
    
    UILabel *qrCoderLaebl = [UILabel labelWithTitle:@"开启二维码" color:UIColorHex(333333) fontSize:15];
    [qrCoderView addSubview:qrCoderLaebl];
    [qrCoderLaebl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(qrCoderView);
    }];
    
    _qrCodeSwitch = [[UISwitch alloc] init];
    _qrCodeSwitch.transform = CGAffineTransformMakeScale(0.8, 0.8);
    _qrCodeSwitch.onTintColor = kMainColor;
    _qrCodeSwitch.on = YES;
    [_qrCodeSwitch addTarget:self action:@selector(qrCodeSwitchClick:) forControlEvents:UIControlEventValueChanged];
    [qrCoderView addSubview:_qrCodeSwitch];
    [_qrCodeSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(qrCoderView).mas_offset(-10);
        make.centerY.equalTo(qrCoderView);
    }];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, waterView.top - 10, self.view.width, _scrollView.bottom - waterView.top)];
    bgView.backgroundColor = kSeparatorColor;
    [_scrollView insertSubview:bgView belowSubview:waterView];
    
    _scrollView.contentSize = CGSizeMake(self.view.width, qrCoderView.bottom + 10);
    
    @weakify(self)
    TTShopCartView *friendsView = [[TTShopCartView alloc] initWithFrame:CGRectMake(0, _scrollView.bottom, self.view.width * 0.5, 85) imageName:@"weixin" title:@"微信好友" clickShopCartBlock:^(TTShopCartView *cartView) {
        @strongify(self)
        [self shareImages];
        
    }];
    [self.view addSubview:friendsView];
    
    TTShopCartView *timeLineView = [[TTShopCartView alloc] initWithFrame:CGRectMake(friendsView.right, friendsView.top, self.view.width * 0.5, friendsView.height) imageName:@"pengyouquan" title:@"朋友圈" clickShopCartBlock:^(TTShopCartView *cartView) {
        @strongify(self)
        [self saveImages];
    }];
    [self.view addSubview:timeLineView];
    
    
}

///微信不支持多图分享，使用系统的分享
- (void)shareImages
{
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:self.chooseImageArray applicationActivities:nil];
    
    ///适配ipad
    UIPopoverPresentationController *popover = activityVC.popoverPresentationController;
    if (popover) {
        popover.sourceView = [UIApplication sharedApplication].keyWindow;
        popover.sourceRect = CGRectMake(0, 0, SCREEN_WIDTH, StatusBarAndNavBar_Height);
        popover.permittedArrowDirections = UIPopoverArrowDirectionLeft;
    }
    
    [self presentViewController:activityVC animated:YES completion:nil];
}

// 保存到相册
- (void)saveImages
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
                [LLAlertUtilies showSystemSetAlertViewWithTitle:@"开启相册权限" message:@"开启后才能保存图片到相册" cancelTitle:nil confirmTitle:@"去开启"];
                
            } else {
                self.saveImagesCount = 0;
                for (UIImage *image in self.chooseImageArray) {
                    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                }
            }
            
        });
        
    }];
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = self.textView.text;
        self.saveImagesCount++;
        if (self.saveImagesCount == self.chooseImageArray.count) {
            
            if (self.sharePopView == nil) {
                self.sharePopView = [TTDetailSharePopView createViewFromNib];
            }
            self.sharePopView.transform = CGAffineTransformIdentity;
            [self.sharePopView showInWindowWithBackgoundTapDismissEnable:YES];
        }
    }
}




- (NSMutableArray<UIImage *> *)chooseImageArray
{
    if (!_chooseImageArray) {
        _chooseImageArray = [NSMutableArray array];
    }
    return _chooseImageArray;
}

- (NSMutableArray<TTImageChooseView *> *)chooseViewArray
{
    if (!_chooseViewArray) {
        _chooseViewArray = [NSMutableArray array];
    }
    return _chooseViewArray;
}

- (NSMutableArray *)imgs
{
    if (!_imgs) {
        _imgs = [NSMutableArray array];
    }
    return _imgs;
}


@end
